#include<iostream>
#include <string>
#include <memory>
#include <cstring>
#include <cerrno>
#include <strings.h>

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>


int main(int argc,char* argv[])
{
    if(argc>3)
    {
        std::cout<<"Usage: "<<argv[0]<<"serverip serverport "<<std::endl;
        exit(2);

    }
    std::string serverip=argv[1];
    uint16_t serverport=std::stoi(argv[2]);


    //创建socket
    int sockfd=::socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd<0)
    {
        std::cerr<<"socket error"<<std::endl;
        exit(2);
    }
    //填充server信息
    struct sockaddr_in poor;
    memset(&poor,0,sizeof(poor));
    poor.sin_family=AF_INET;
    poor.sin_port=::htons(serverport);
    poor.sin_addr.s_addr=::inet_addr(serverip.c_str());

    while(true)
    {
        std::cout<<"Please Enter# ";
        std::string message;
        std::getline(std::cin,message);

        int n=::sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&poor,sizeof(poor));
        (void)n;

        sockaddr_in temp;
        socklen_t len=sizeof(temp);
        char buff[1024];

        n=::recvfrom(sockfd,buff,sizeof(buff)-1,0,(struct sockaddr*)&temp,&len);
        if(n>0)
        {
            buff[n]=0;
            std::cout<<buff<<std::endl;
        }
    }

    return 0;
}